/**
 * Copyright (C) 2011  Robin Dietrich, Nils Kenneweg, Leonard Stutz
 * 
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 * 
 **/ 

#include "config.hpp"

#include <fstream>
#include <boost/filesystem.hpp>

#include <iostream>
#include <stdlib.h>
#include <string>

#include "chunk.hpp"
#include "mapGenerator.hpp"
 
namespace minecraft {
	chunk::chunk(int x, int y, int z) : data(boost::extents[P_CHUNKSIZE][P_CHUNKSIZE][P_CHUNKSIZE]) {
        //set chunk position
        this->id.x = x;
        this->id.y = y;
        this->id.z = z;
        
        //chunk id
        this->id.id = coordinatesToChunkId(x, y, z);
        
        //set changed to false
        this->changed = false;
        
        //if the data for this chunk was already generated, load it from disk
        boost::filesystem::path p(std::string(P_ROOT)+"data/"+this->id.id);
        if (boost::filesystem::is_regular_file(p)) {  
            //std::cout << "loading chunk " << this->id.id << " from cache" << std::endl;
		
			#ifdef __MINGW32__
				size_t origsize = wcslen(p.c_str()) + 1;
				size_t convertedChars = 0;
				char nstring[origsize];
				wcstombs(nstring, p.c_str(), origsize);
			
				std::ifstream in(nstring);
			#else
				std::ifstream in(p.string().c_str());
			#endif
            boost::archive::text_iarchive ia(in);            
			data_lock.lock();
				ia >> this->data;
			data_lock.unlock();
            in.close();
        } else {
            //std::cout << "loading chunk " << this->id.id << " from generator" << std::endl;
            //prior to generation, set all values to 0
            //for (unsigned int i = 0; i < P_CHUNKSIZE; ++i) {
            //    for (unsigned int j = 0; j < P_CHUNKSIZE; ++j) {
            //        for (unsigned int k = 0; k < P_CHUNKSIZE; ++k) {
            //            this->data[i][j][k] = 0; 
            //        }
            //    }
            //}
            
			data_lock.lock();
				sMapGenerator::Instance()->generate(this->data, x, y, z);
			data_lock.unlock();
            
            //has been changed
            this->changed = true;
        }
        
        //rebuild type array
        this->rebuildTypes();
	}
	
	chunk::~chunk() {
        //save chunk to disk if modified
        if (this->changed && false) {
            std::cout << "saving chunk " << this->id.id << std::endl;
            boost::filesystem::path p(std::string(P_ROOT)+"data/"+this->id.id);
			
			#ifdef __MINGW32__
				size_t origsize = wcslen(p.c_str()) + 1;
				size_t convertedChars = 0;
				char nstring[origsize];
				wcstombs(nstring, p.c_str(), origsize);
				
				std::ofstream out(nstring);
			#else
				std::ofstream out(p.string().c_str());
			#endif
            boost::archive::text_oarchive output(out);
			data_lock.lock();
				output << this->data;
			data_lock.unlock();
            out.close();
        } else {
            //std::cout << "chunk " << this->id.id << " not modified" << std::endl;
        }        
	}
    
    b_type chunk::get(int x, int y, int z) {
		data_lock.lock();
			b_type block = this->data[x][y][z];
		data_lock.unlock();
        return block;
    }
    
    void chunk::update(int x, int y, int z, b_type val) {
		{
			data_lock.lock();
				this->data[x][y][z] = val;
			data_lock.unlock();
		}
        this->changed = true;
        
        if (this->types.find(val) == this->types.end()) {
            this->types.insert(val);
        }
    }
    
    void chunk::rebuildTypes() {
        this->types.clear();
        //for (unsigned int i = 0; i < P_CHUNKSIZE; ++i) {
        //    for (unsigned int j = 0; j < P_CHUNKSIZE; ++j) {
        //        for (unsigned int k = 0; k < P_CHUNKSIZE; ++k) {
        //            if (this->data[i][j][k] == 0) continue; //dont add air to type list
        //            if (this->types.find(this->data[i][j][k]) == this->types.end()) {
        //                this->types.insert(this->data[i][j][k]);
        //            }
        //        }
        //    }
        //}
        
        this->types.insert(1);
        this->types.insert(2);
        this->types.insert(3);
        this->types.insert(4);
    }
}
